package boot

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"sync"
	"user-server/src/util"
	"xorm.io/xorm"
)

type Orm struct {
	*xorm.Engine
}

var (
	dbEngine *Orm
	dbOnce   sync.Once
)

func GetOrmEngine() *Orm {
	return dbEngine
}

func NewOrmEngine() {
	appInfo := util.GetYamlConfig()

	url := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", appInfo.MySql.UserName, appInfo.MySql.Password, appInfo.MySql.Host, appInfo.MySql.Port, appInfo.MySql.DataBase)
	engine, err := xorm.NewEngine(appInfo.MySql.DriverName, url)
	if err != nil {
		log.Panic(err.Error())
		return
	}
	engine.ShowSQL(false)
	//单例模式
	dbOnce.Do(func() {
		orm := new(Orm)
		orm.Engine = engine
		dbEngine = orm
	})
}

func CloseOrmEngine() {
	if dbEngine == nil {
		return
	}
	if err := dbEngine.Close(); nil != err {
		log.Printf("Disconnect from database failed: %s", err.Error())
	}
}
